package engine.audio;

/**
 * Mixer
 * Used for mixing multiple AudioBuffer_I's into a single audiobuffer.
 **/
public final class Mixer extends AudioBuffer {
	/**
	 * CtoR
	 * @param bufferSize - size of the buffer, in bytes.
	 **/
	public Mixer(int bufferSize) {
		super(bufferSize);
	}
	
	/**
	 * Mixes an array of AudioBuffer_I's into the Mixer's local buffer.
	 * @param channels - An array of AudioBuffer_I's to mix
	 * @param length - the number of samples to drain from each channel and mix.
	 * @return The number of samples mixed.
	 **/
	public int mix(AudioBuffer_I[] channels, int length) {
		if(channels == null) {
			return 0;
		}
		if(length == 0) {
			return 0;
		}
		byte[] workBuffer;
		channels[0].drain(this._Buffer, length);
		if(channels.length > 1) {
			workBuffer = new byte[length];
			for(int i = 1; i < channels.length; i++) {
				channels[i].drain(workBuffer, length);
				for(int j = 0; j < length; j++) {
					this._Buffer[j] += workBuffer[j];
				}
			}
		}
		this._Tail = length;
		return length;
	}
}